const puppeteer = require('puppeteer');
const db = require("./db")
async function task(urls, workPlace) {

    //executablePath: workPlace    
    const browserFetcher = puppeteer.createBrowserFetcher();
    const revisionInfo = await browserFetcher.download('533271')
    //userDataDir: workPlace , 
    let browser = null;
    try {
        browser = await puppeteer.launch({ headless: false, userDataDir: workPlace, ignoreDefaultArgs: true, executablePath: revisionInfo.executablePath });
        for (const url of urls) {
            try {
                console.log("down:" + url)
                const page = await browser.newPage();
                await page.goto(url);
                await page.waitForSelector('body');
                await page.evaluate(() => {
                    localStorage.clear();
                    sessionStorage.clear();
                    function clearCookie() {
                        var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
                        if (keys) {
                            for (var i = keys.length; i--;)
                                document.cookie = keys[i] + '=0;expires=' + new Date(1524413738).toUTCString()
                        }
                    }
                    clearCookie();
                });
                await page.click("#free_down_link", { delay: 20 });
                //var response = await page.waitForNavigation({ waitUntil: "networkidle" });

                //await wait(500);  
                // page.on('dialog', async dialog => {
                //     console.log(1)
                //     console.log(dialog.message());
                //     await dialog.dismiss();
                //     await browser.close();
                //   });
                //await wait(2000);  
            } catch (err) {
                console.error(err)
            }
        }

        try {
            await browser.close();
            await wait(2);
            process.kill(browser.process().pid, 'SIGTERM');
        } catch (err) {
            await wait(1);
            process.kill(browser.process().pid, 'SIGTERM');
        }

    } catch (err) {
       throw err;
    }

}

async function tasks(ip) {
    let urls = await db.getUrls(ip);
    let urlDos = await db.getDoUrls(ip);
    let urlTasks = []
    for (const iterator of urls) {
        if (findIsNotIn(iterator.url, urlDos)) {
            urlTasks.push(iterator.url);
            await db.recordsTask({
                ip,
                url: iterator.url
            })
        }
    }

    try {
        let workPlace = 'D://brower/wydTest';
        await task(urlTasks, workPlace);
    } catch (err) {
        console.error(err)
    }
}

function wait(m) {
    return new Promise(function (resolve, reject) {
        let t = setTimeout(async function () {
            clearTimeout(t);
            resolve("ok");
        }, m * 1000)
    })
}

function findIsNotIn(ele, list) {
    for (const iterator of list) {
        if (ele == iterator.url) {
            return false;
        }
    }
    return true;
}



module.exports = {
    tasks,
}